package cn.janescott.inner.space.webapp.adapter;

import cn.janescott.inner.space.data.system.dto.UserSummaryDTO;
import cn.janescott.inner.space.data.system.facade.SystemFacade;
import cn.janescott.inner.space.shiro.aop.AuthenAnnotation;
import cn.janescott.inner.space.shiro.aop.AuthenAspect;
import cn.janescott.inner.space.shiro.realm.RealmHandler;
import cn.janescott.inner.space.shiro.token.UsernamePasswordCodeToken;
import com.alibaba.dubbo.config.annotation.Reference;
import org.apache.shiro.authc.*;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 数据库处理器
 *
 * @author scott
 * @date 2018/7/30
 */
@Component
public class DatabaseRealmHandler implements RealmHandler {

    @Reference(interfaceClass = SystemFacade.class, check = false)
    private SystemFacade systemFacade;

    @AuthenAnnotation(targetClass = DatabaseRealmHandler.class, message = "获取用户信息")
    @Override
    public UsernamePasswordToken getToken(String username) {
        UserSummaryDTO userSummaryDTO = systemFacade.findSummaryByUsername(username);
        //用户名错误
        if (null == userSummaryDTO || null == userSummaryDTO.getUser()) {
            throw new UnknownAccountException();
        }
        //账户未初始化
        if (null == userSummaryDTO.getAccount()) {
            throw new AccountException();
        }
        //账户锁定
        if (userSummaryDTO.getAccount().isLocked()) {
            throw new LockedAccountException();
        }
        //账户禁用
        if (null != userSummaryDTO.getAccount().getFrozen() &&
                new Date().before(userSummaryDTO.getAccount().getFrozen())) {
            throw new DisabledAccountException();
        }

        return UsernamePasswordCodeToken.build()
                .username(userSummaryDTO.getUser().getUsername())
                .password(userSummaryDTO.getUser().getPassword().toCharArray());
    }
}
